package com.weir.quarkus.base.system.utils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import io.vertx.core.http.HttpServerRequest;

/**
 * 
 * @ClassName: IpUtil
 * @Description: IP 工具类
 * @author weir
 * @date 2021年8月25日
 *
 */
public class IpUtil {

	private IpUtil() {
	}

	private static String getIp(HttpServerRequest request) {
		List<String> keyList = Arrays.asList("X-Client-IP", "X-Real-IP", "X-Real-Ip", "WL-Proxy-Client-IP",
				"PROXY_CLIENT_IP", "X_Forwarded_For");

		for (String key : keyList) {
			String ip = request.getHeader(key);
			// 是合法的 IP，直接返回
			if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
				return ip;
			}
		}

		return request.remoteAddress().hostAddress();
	}

	public static String getSingleIp(HttpServerRequest request) {
		String ip = getIp(request);

		if (ip.contains(",")) {
			return ip.split(",")[0];
		}

		return ip;
	}

	public static Map<String, String> getAllIpInfo(HttpServerRequest request) {
		Map<String, String> map = new HashMap<>();
		map.put("X-Client-IP", request.getHeader("X-Client-IP"));
		map.put("X-Real-IP", request.getHeader("X-Real-IP"));
		map.put("X-Real-Ip", request.getHeader("X-Real-Ip"));
		map.put("WL-Proxy-Client-IP", request.getHeader("WL-Proxy-Client-IP"));
		map.put("PROXY_CLIENT_IP", request.getHeader("PROXY_CLIENT_IP"));
		map.put("X_Forwarded_For", request.getHeader("X_Forwarded_For"));
		map.put("RemoteAddress", request.remoteAddress().host());
		return map;
	}

}